package com.baixun.gassystem.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baixun.gascommon.config.ApiConfig;
import com.baixun.gascommon.utils.HttpClientUtil;
import com.baixun.gascommon.utils.RedisUtils;
import com.baixun.gasentity.dto.BackOfficeUserInfo;
import com.baixun.gasentity.entity.SysDepartment;
import com.baixun.gassystem.mapper.BackOfficeUserInfoMapper;
import com.baixun.gassystem.mapper.SysDepartmentMapper;
import com.baixun.gassystem.service.ApiService;
import com.baixun.gassystem.service.BackOfficeUserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @program: 上海燃气驾驶舱
 * @description:后台管理系统用户管理的用户信息
 * @author: yesong
 **/
@Service
public class BackOfficeUserInfoServiceImpl extends ServiceImpl<BackOfficeUserInfoMapper, BackOfficeUserInfo> implements BackOfficeUserInfoService{

    @Autowired
    private BackOfficeUserInfoMapper backOfficeUserInfoMapper;

    @Autowired
    private ApiService apiService;

    @Autowired
    private  RedisUtils redisUtils;

    private static final String TOKEN_KEY = "SAAS_SESSION_TOKEN";

    /**
     * 调用evs接口获取用户信息【不保存本地】
     * @return
     */
    @Override
    public List<String> getAllUserInfo() throws Exception {
        // Step 1: 调用接口获取所有部门和用户数据
        String users = apiService.getUsersFromAllDepartments().toString();

        // Step 2: 解析返回的 JSON 数据为 JSONArray
        JSONArray dataArray = JSONArray.parseArray(users);

        // 如果 data 数据为空，返回空列表
        if (dataArray == null || dataArray.isEmpty()) {
           new Exception("No users found in response.");
            return new ArrayList<>();
        }

        // Step 3: 提取所有用户的 userId，去重处理
        Set<Long> uniqueUserIds = new HashSet<>();
        for (int i = 0; i < dataArray.size(); i++) {
            JSONObject userJson = dataArray.getJSONObject(i);
            Long userId = userJson.getLong("userId");
            if (userId != null) {
                uniqueUserIds.add(userId); // 使用 Set 去重
            }
        }

        // Step 4: 使用去重后的 userId 列表逐一调用用户详情接口
        List<String> allUserInfo = new ArrayList<>();
        String token = redisUtils.get(TOKEN_KEY);
        if (token == null) {
            throw new Exception("No valid token found in Redis, please check if the token is refreshed.");
        }

        for (Long userId : uniqueUserIds) {
            // 构建访问用户详情接口的 URL
            String userInfoUrl = ApiConfig.DOMAIN + ApiConfig.USERS_API + userId;

            // 构建请求头信息，包含从 Redis 获取的 token
            HashMap<String, String> headers = new HashMap<>();
            headers.put("Cookie", "SAAS_SESSION=" + token);
            headers.put("Content-Type", "application/json; charset=UTF-8");

            // 调用接口获取用户信息
            String response = HttpClientUtil.sendGetRequest(userInfoUrl, headers);

            // 将用户信息加入结果列表
            allUserInfo.add(response);
        }

        // Step 5: 返回所有用户信息
        return allUserInfo;
    }

    @Override
    public String getUserInfoToName(String name) {
        return null;
    }


    /**
     * 查询所有人员的所属层级
     * 用userid去重
     */
    @Override
    public List<SysDepartment> getDepartmentTree() throws Exception {
        // 调用接口获取部门数据
        String departmentsResponse = apiService.getUsersFromAllDepartments().toString();

        // Step 1: 将响应数据解析为 JSONArray
        JSONArray dataArrays = JSONArray.parseArray(departmentsResponse);

        // 用于存储最终的部门列表
        Map<Long, SysDepartment> departmentMap = new HashMap<>();
        // 用于存储已处理的 userId，确保去重
        Set<Long> processedUserIds = new HashSet<>();

        // Step 2: 遍历每个对象，直接提取字段
        for (int i = 0; i < dataArrays.size(); i++) {
            JSONObject departmentJson = dataArrays.getJSONObject(i);

            // 提取字段信息
            Long departmentId = departmentJson.getLong("departmentId");
            String departmentName = departmentJson.getString("departmentName");
            Long parentId = departmentJson.getLong("parentId");
            Long userId = departmentJson.getLong("userId"); // 获取 userId 以便去重

            // 如果 userId 已经处理过，跳过
            if (processedUserIds.contains(userId)) {
                continue; // 跳过本次循环
            }
            // 将 userId 添加到已处理集合中
            processedUserIds.add(userId);

            // 如果 Map 中没有该部门，添加新的 SysDepartment 对象
            if (!departmentMap.containsKey(departmentId)) {
                SysDepartment department = new SysDepartment();
                department.setId(departmentId);
                department.setName(departmentName);
                department.setParentId(parentId); // 如果有父节点 ID，则设置
                departmentMap.put(departmentId, department);
            }
        }

        // Step 3: 构建部门树
        List<SysDepartment> rootDepartments = new ArrayList<>();
        for (SysDepartment department : departmentMap.values()) {
            Long parentId = department.getParentId();
            if (parentId != null && parentId != 0) {
                // 找到父部门并添加为其子部门
                SysDepartment parent = departmentMap.get(parentId);
                if (parent != null) {
                    parent.getChildren().add(department);
                }
            } else {
                // 如果是顶级部门，加入根部门列表
                rootDepartments.add(department);
            }
        }

        // Step 4: 返回完整的部门树
        return rootDepartments;
    }

}


